package com.yonyou.ucf.mdf.app.isvdxq.firstpart.location.controller;

import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.core.type.TypeReference;
import com.google.gson.Gson;
import com.yonyou.ucf.mdf.app.isvdxq.ReturnResult.DataResult;
import com.yonyou.ucf.mdf.app.isvdxq.common.DxqConfig;
import com.yonyou.ucf.mdf.app.isvdxq.firstpart.location.entity.OrderNoticeEntity;
import com.yonyou.ucf.mdf.app.isvdxq.firstpart.location.model.OrderStoreAddBean;
import com.yonyou.ucf.mdf.app.isvdxq.firstpart.location.model.OrderStoreOutBean;
import com.yonyou.ucf.mdf.app.isvdxq.firstpart.location.service.OrderNoticeService;
import com.yonyou.ucf.mdf.app.isvdxq.firstpart.location.service.OrderStoreService;
import com.yonyou.ucf.mdf.app.isvdxq.other.service.BaseService;
import com.yonyou.ucf.mdf.app.isvdxq.other.service.ProductService;
import com.yonyou.ucf.mdf.app.isvdxq.utils.RequestTool;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@RequestMapping(value = {DxqConfig.pre_apiUrl+"/orderstore",DxqConfig.pre_pcUrl+"/orderstore"})
public class OrderStoreController {
    private static final Logger logger = LoggerFactory.getLogger(OrderStoreController.class);

    @Autowired
    private BaseService baseService;
    @Autowired
    private OrderNoticeService orderNoticeService;
    @Autowired
    private ProductService productService;
    @Autowired
    private OrderStoreService orderStoreService;

    /**
     * 采购入库审核 主单、详单
     * 出入单据记录添加
     */
    @RequestMapping("/saveorderstoreadd")
    public DataResult saveorderstorein(HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> params;
        DataResult result = new DataResult();
        try {
            String tenantId = baseService.getTenantId(request);
            String userId = RequestTool.getHeaderAndParameter(request, DxqConfig.DXQ_userId);
            System.out.println("[saveorderstoreadd]");
            List<OrderStoreAddBean> dataList = new ArrayList<>();
            boolean isJsonReq = RequestTool.isJsonReq(request);
            params = RequestTool.getParams(request);
            String dataListStr = (String) params.get("dataList");
            Object userInfo = params.get("userInfo");
            String actioncode = (String) params.get("actioncode");
            String billnum = (String) params.get("billnum");
            if (StringUtils.isNotEmpty(dataListStr)) {
                dataList = RequestTool.getBean(dataListStr, new TypeReference<List<OrderStoreAddBean>>() {});
            }
            if (dataList == null || dataList.size() == 0) {
                return result;
            }
            List<OrderNoticeEntity> recordEntitys = new ArrayList<>();
            // 本地通知写入
            for (OrderStoreAddBean item : dataList) {
                OrderNoticeEntity recordEntity = new OrderNoticeEntity();
                recordEntity.setTenant_id(tenantId);
                recordEntity.setOrderid(String.valueOf(item.getId()));
                recordEntity.setOrderdetailids("");
                recordEntity.setActioncode(actioncode);
                recordEntity.setTranstype(billnum);
                recordEntity.setPickbatchno("");
                recordEntity.setType(DxqConfig.TypeOutIn); //本地回写失败
                recordEntity.setRemarkyonyou(dataListStr);
                recordEntity.setRemarkdxq(JSONObject.toJSONString(userInfo));
                recordEntity.setRemark(result.getMessage());
                recordEntity.setModifier(userId);
                recordEntity.setStatus(result.getStatus());
                recordEntitys.add(recordEntity);
            }
            int rInt = orderNoticeService.InsertBatch(recordEntitys);
            String orderIds = dataList.stream().map(it -> String.valueOf(it.getId())).collect(Collectors.joining(","));
            System.out.println(String.format("[saveorderstoreadd 2] %s", rInt, orderIds));
            result = new DataResult(1, "操作成功");
        } catch (Exception ex) {
            result = new DataResult(0, ex.getMessage());
            String logtxt = "[saveorderstorein-ex]" + new Gson().toJson(ex);
            logger.info(logtxt);
            System.out.println(logtxt);
        } finally {
            return result;
        }
    }

    /**
     * 出入记录取消
     */
    @RequestMapping(value = "/saveorderstoredel", method = RequestMethod.POST)
    public DataResult saveorderstoredel(HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> params;
        DataResult result = new DataResult();
        try {
            String tenantId = baseService.getTenantId(request);
            String userId = RequestTool.getHeaderAndParameter(request, DxqConfig.DXQ_userId);
            logger.info("[saveorderstoredel]");
            List<OrderStoreAddBean> dataList = new ArrayList<>();
            boolean isJsonReq = RequestTool.isJsonReq(request);
            params = RequestTool.getParams(request);
            String dataListStr = (String) params.get("dataList");
            Object userInfo = params.get("userInfo");
            String actioncode = (String) params.get("actioncode");
            String billnum = (String) params.get("billnum");
            if (StringUtils.isNotEmpty(dataListStr)) {
                dataList = RequestTool.getBean(dataListStr, new TypeReference<List<OrderStoreAddBean>>() {
                });
            }
            if (dataList == null || dataList.size() == 0) {
                return result;
            }
            String transtype = billnum;
            List<String> strList = dataList.stream().map(it -> String.valueOf(it.getId())).collect(Collectors.toList());
            List<OrderNoticeEntity> orderNoticeEntities = orderNoticeService.SelectByType(strList, transtype, DxqConfig.TypeOutIn, tenantId);
            if (orderNoticeEntities.size() > 0) {
                List<Integer> ids = orderNoticeEntities.stream().map(it -> it.getId()).collect(Collectors.toList());
                int rInt = orderNoticeService.DelEntitys(ids, tenantId);
                System.out.println(String.format("[saveorderstoredel 2]%s", rInt));
            }
            result = new DataResult(1, "操作成功");
        } catch (Exception ex) {
            result = new DataResult(0, ex.getMessage());
            String logtxt = "[saveorderstorein-ex]" + new Gson().toJson(ex);
            logger.info(logtxt);
            System.out.println(logtxt);
        } finally {
            return result;
        }
    }

    /**
     * 销售出库审核 主单、详单
     */
    @RequestMapping(value = "/saveorderstoreout", method = RequestMethod.POST)
    public DataResult saveorderstoreout(HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> params;
        DataResult result = new DataResult();
        try {
            String tenantId = baseService.getTenantId(request);
            String userId = RequestTool.getHeaderAndParameter(request, DxqConfig.DXQ_userId);
            logger.info("[saveorderstoreout]");
            List<OrderStoreOutBean> dataList = new ArrayList<>();
            boolean isJsonReq = RequestTool.isJsonReq(request);
            params = RequestTool.getParams(request);
            String dataListStr = (String) params.get("dataList");
            Object userInfo = params.get("userInfo");
            String actioncode = (String) params.get("actioncode");
            String billnum = (String) params.get("billnum");
            if (StringUtils.isNotEmpty(dataListStr)) {
                dataList = RequestTool.getBean(dataListStr, new TypeReference<List<OrderStoreOutBean>>() {
                });
            }
            if (dataList == null || dataList.size() == 0) {
                return result;
            }

            // 本地通知写入
            OrderNoticeEntity recordEntity = new OrderNoticeEntity();
            recordEntity.setTenant_id(tenantId);
            recordEntity.setOrderid("");
            recordEntity.setOrderdetailids("");
            recordEntity.setActioncode(actioncode);
            recordEntity.setTranstype(billnum);
            recordEntity.setPickbatchno("");
            recordEntity.setType(DxqConfig.TypeOutIn); //本地回写失败
            recordEntity.setRemarkyonyou(dataListStr);
            recordEntity.setRemarkdxq(JSONObject.toJSONString(userInfo));
            recordEntity.setRemark(result.getMessage());
            recordEntity.setModifier(userId);
            recordEntity.setStatus(result.getStatus());
            int rInt = orderNoticeService.InsertEntity(recordEntity);
            System.out.println(String.format("[saveorderstoreout2]%s", rInt));
//            String access_token = baseService.getAccessToken3(tenantId).getAccessToken();
//            String gatewayUrl = baseService.buildBusinessUrl(tenantId);
//            boolean rFlag = orderStoreService.AutoDataOutByOrderId(access_token, orderId, userId, gatewayUrl);
            result = new DataResult(1, "操作成功");
        } catch (Exception ex) {
            result = new DataResult(0, ex.getMessage());
            String logtxt = "[saveorderstorein-ex]" + new Gson().toJson(ex);
            logger.info(logtxt);
            System.out.println(logtxt);
        } finally {
            return result;
        }
    }
}
